package cn.czu.wyw.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author wyw
 * @Description
 * @Date 2021/3/15 11:38
 * @Version 1.0
 */
@Slf4j
@Aspect
@Component
public class LogAnnotationAspect {
    @Pointcut("@annotation(cn.czu.wyw.annocation.LogAnnotation)")
    public void logPoint() {
    }



    @Around("logPoint()")
    public Object logAroung(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StopWatch sw = new StopWatch();
        sw.start();
        Object result;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容//url
//        log.info("url ={}",request.getRequestURI());
//        log.info("method={}",request.getMethod());
//        log.info("ip={}",request.getRemoteAddr());
//        log.info("class_method={}",proceedingJoinPoint.getSignature().getDeclaringTypeName()+'.'+ proceedingJoinPoint.getSignature().getName());
//        log.info("args={}",proceedingJoinPoint.getArgs());
//        Enumeration<String> enu = request.getParameterNames();
//        while (enu.hasMoreElements()) {
//            String name = (String) enu.nextElement();
//            log.info("name:{},value:{}", name, request.getParameter(name));
//        }
        // end
        log.info("请求开始，ip为：{}，请求类型：{}，请求入口{}", request.getRemoteAddr(), request.getMethod(), request.getRequestURI());
        log.info("类方法为：{}.{}() 参数={}", proceedingJoinPoint.getSignature().getDeclaringType(),
                proceedingJoinPoint.getSignature().getName(), Arrays.asList(proceedingJoinPoint.getArgs()));
        try {
            result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
            sw.stop();
            log.info("请求结束,耗时{}毫秒", sw.getLastTaskTimeMillis());
        } catch (Exception e) {
            log.error("---请求错误，请求入口:{}.{}() 参数={}，错误为:{}", proceedingJoinPoint.getSignature().getDeclaringType(),
                    proceedingJoinPoint.getSignature().getName(), Arrays.asList(proceedingJoinPoint.getArgs()), e.getMessage());
            result = "请求错误";
        }
        return result;
    }
}
